{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "d9ac0c38-8e17-456e-b05c-baa0b94ae69b",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "# 加载数据集\n",
    "vehicle_data = pd.read_csv('train.csv')\n",
    "vehicle_test_data = pd.read_csv(\"test.csv\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7489eb74-ff61-4f98-bc40-dcefdee89f2f",
   "metadata": {},
   "source": [
    "# 数据预处理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "1281fed0-6f54-4fff-bea8-09a65f2e73ef",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.preprocessing import LabelEncoder\n",
    "\n",
    "# 预处理数据\n",
    "\n",
    "# Step 1: Convert the \"running\" column to a uniform unit (kilometers)\n",
    "# Extract numeric values and handle units (assuming 1 mile = 1.60934 km)\n",
    "def convert_to_km(value):\n",
    "    if \"miles\" in value:\n",
    "        return float(value.split()[0].replace(',', '')) * 1.60934  # convert miles to km\n",
    "    elif \"km\" in value:\n",
    "        return float(value.split()[0].replace(',', ''))  # already in km\n",
    "    return None\n",
    "\n",
    "vehicle_data['running_km'] = vehicle_data['running'].apply(convert_to_km)\n",
    "vehicle_test_data['running_km'] = vehicle_test_data['running'].apply(convert_to_km)\n",
    "\n",
    "# Drop the original \"running\" column as it is now redundant\n",
    "vehicle_data = vehicle_data.drop(columns=['running'])\n",
    "vehicle_test_data = vehicle_test_data.drop(columns=['running'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "7b0497b3-a7f8-4da3-98fc-9b0417b46863",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Step 2: Encode categorical variables using LabelEncoder\n",
    "label_encoders = {}\n",
    "categorical_columns = ['model', 'motor_type', 'wheel', 'color', 'type', 'status']\n",
    "\n",
    "for column in categorical_columns:\n",
    "    le = LabelEncoder()\n",
    "    vehicle_data[column] = le.fit_transform(vehicle_data[column])\n",
    "    label_encoders[column] = le  # save the encoder for reference\n",
    "    vehicle_test_data[column] = le.fit_transform(vehicle_test_data[column])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "219c43d9-5474-43b5-b9b7-483921751383",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(   model  year  motor_type  wheel  color  type  status  motor_volume  price  \\\n",
       " 0      4  2022           3      0     15     5       1           2.0  24500   \n",
       " 1      2  2014           3      0      1     5       1           2.0  25500   \n",
       " 2      1  2018           3      0     10     5       1           2.0  11700   \n",
       " 3      2  2002           3      0      6     5       1           3.2  12000   \n",
       " 4      2  2017           3      0      1     5       2           2.0  26000   \n",
       " \n",
       "    running_km  \n",
       " 0     3000.00  \n",
       " 1   132000.00  \n",
       " 2   152887.30  \n",
       " 3   220479.58  \n",
       " 4   130000.00  ,\n",
       " (1313, 9),\n",
       " (329, 9),\n",
       " (1313,),\n",
       " (329,))"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Step 3: Select features for the model\n",
    "features = vehicle_data[['model', 'year', 'motor_type', 'wheel', 'color', 'type', 'status', 'motor_volume', 'running_km']]\n",
    "target = vehicle_data['price']\n",
    "\n",
    "# Split the data into training and test sets\n",
    "X_train, X_test, y_train, y_test = train_test_split(features, target, test_size=0.2, random_state=42)\n",
    "\n",
    "# Display the preprocessed data structure and feature-target split\n",
    "vehicle_data.head(), X_train.shape, X_test.shape, y_train.shape, y_test.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2cb3a1f2-04ee-4197-88f0-24196a2414e6",
   "metadata": {},
   "source": [
    "# 构建SVM模型并评估"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "eabce6a8-f29a-451d-a602-67d6cfe3dabd",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(42783487.060854115, 0.02781126278729018)"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn.svm import SVR\n",
    "from sklearn.metrics import mean_squared_error, r2_score\n",
    "\n",
    "# Train a svm\n",
    "svm = SVR()\n",
    "svm.fit(features, target)\n",
    "\n",
    "# Make predictions on the test set\n",
    "y_pred = svm.predict(X_test)\n",
    "\n",
    "# Evaluate the model using Mean Squared Error and R-squared metrics\n",
    "mse = mean_squared_error(y_test, y_pred)\n",
    "r2 = r2_score(y_test, y_pred)\n",
    "\n",
    "mse, r2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "82847bc1-3f89-48df-a43d-e8aef2e3ac7b",
   "metadata": {},
   "source": [
    "# 预测价格"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "08ad965f-e299-4e79-af5f-8261a44e0c84",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "feature_test=vehicle_test_data[['model', 'year', 'motor_type', 'wheel', 'color', 'type', 'status', 'motor_volume', 'running_km']]\n",
    "sub=svm.predict(feature_test) # 预测\n",
    "# 将预测结果写入csv文件\n",
    "sub=sub.astype(int)\n",
    "pd_sub=pd.DataFrame(sub,columns=[ \"price\"])\n",
    "pd_sub.insert(0, 'Id',pd.Series(range(411)))\n",
    "pd_sub.to_csv(\"submission_svm.csv\", sep=',', index=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "d08300ef-c123-486d-8372-c0cb3ef04308",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "b0b4bdd0-e654-4a64-b566-19e4bcc612b9",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "a82f64f0-8ce4-4162-b93d-377531e99951",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "d1efe93f-7752-44c8-a8c0-5db3267e5d9b",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1c8fb022-d01e-4054-9a3b-de09dab05482",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
